<template>
  <div>
    <el-dialog :title="shareTitle" :visible.sync="dialogVisible" width="95%" :before-close="handleCancle">
      <el-form ref="searchForm" :model="formInline" label-width="80px" label-position="left" style="padding: 0 20px" :rules="searchRules">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="成员类型" prop="type">
              <el-select v-model="formInline.type" size="small" @change="selectType" class="input">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="中文名" prop="chiName">
              <el-input v-model="formInline.chiName" size="small" class="input" @keyup.enter.native="handleSearch('searchForm')"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="英文名" prop="engName">
              <el-input v-model="formInline.engName" size="small" class="input" @keyup.enter.native="handleSearch('searchForm')"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <div style="margin-top: 5px">
              <el-button icon="el-icon-search" type="primary" size="small" @click="handleSearch('searchForm')">查询</el-button>
              <el-button icon="el-icon-plus" v-if="addShowBtn" type="primary" size="small" @click="handleAdd">新增</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <div ref="ref" class="table-box">
        <TableComponent :height="height" v-if="ifPeople" :columns="dialogTableColumns" :data="dialogtableData" :tableOption="dialogtableOption" @rowClick="rowClick"></TableComponent>
        <TableComponent :height="height" v-if="ifCompany" :columns="dialogTableColumnsComponty" :data="dialogtableDataComponty" :tableOption="dialogtableOption" @rowClick="rowClick"></TableComponent>
      </div>
      <span slot="footer">
        <el-button @click="handleCancle">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 新增他方企业弹窗 -->
    <el-dialog title="新增他方企业" :visible.sync="dialogVisibleLegal" width="60%" :before-close="handleCancleLegal">
      <el-form ref="form" :model="form" label-width="100px" style="padding: 0 30px;" label-position="left">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="注册中文名" prop="companyChiName" style="margin-left: -9px">
              <el-input class="input" v-model="form.companyChiName" size="medium" style="margin-left: 9px; width: calc(100% - 9px)"></el-input>
            </el-form-item>
            <el-form-item label="注册地区" prop="location">
              <el-cascader v-model="form.location" :options="locationOptions" :props="prop" size="medium" class="select" filterable></el-cascader>
            </el-form-item>
            <el-form-item label="注册类型" prop="registerType">
              <el-select v-model="form.registerType" class="select" size="medium">
                <el-option v-for="item in registerTypeOptions" :key="item.value" :label="item.value" :value="item.code"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="注册英文名" prop="companyEngName">
              <el-input class="input" v-model="form.companyEngName" size="medium"></el-input>
            </el-form-item>
            <el-form-item label="国有出资情形" prop="stateEnterpreiseCapi">
              <el-select v-model="form.stateEnterpreiseCapi" class="select" size="medium">
                <el-option v-for="item in stateEnterpreiseCapi" :key="item.value" :label="item.value" :value="item.code"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="新增日期" prop="registerId">
              <el-date-picker v-model="form.addDate" type="date" placeholder="选择日期" format="yyyy 年 MM 月 dd 日" size="medium" class="select" value-format="yyyy-MM-dd"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCancleLegal">取 消</el-button>
        <el-button type="primary" @click="handleSubmitLegal">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 新增自然人弹窗 -->
    <el-dialog title="新增自然人" :visible.sync="dialogVisibleNatural" width="60%" :before-close="handleCancleNatural">
      <el-form ref="formNatural" :model="formNatural" label-width="120px" :rules="rules" label-position="left" style="padding: 0 40px;">
        <el-row :gutter="40">
          <el-col :span="12">
            <el-form-item label="姓名" prop="nameChi">
              <el-input class="input" v-model="formNatural.nameChi" size="small"></el-input>
            </el-form-item>
            <el-form-item label="是否招商局员工" prop="ifcmhk">
              <el-select v-model="formNatural.ifcmhk" :class="[ifBtn?'select-btn':'select']" size="small" @change="cmhkChange">
                <el-option v-for="item in ifcmhkOption" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
              <el-button v-if="ifBtn" type="text" size="mini" @click="selectNum">查询工号</el-button>
            </el-form-item>
            <el-form-item label="招商局员工号" prop="cmhkPersonId" v-show="ifCmhkPeople">
              <el-input v-model="formNatural.cmhkPersonId" class="select" size="small"></el-input>
            </el-form-item>
            <el-form-item label="所属地区" prop="location">
              <el-cascader v-model="formNatural.location" :options="locationOptions" :props="prop" size="small" class="select" filterable></el-cascader>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input class="input" v-model="formNatural.email" size="small"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="英文名称" prop="nameEng">
              <el-input class="input" v-model="formNatural.nameEng" size="small"></el-input>
            </el-form-item>
            <el-form-item label="性别" prop="sex">
              <el-select v-model="formNatural.sex" placeholder="请选择" class="select" size="small">
                <el-option label="男" value="M"></el-option>
                <el-option label="女" value="F"></el-option>
                <el-option label="未知" value="U"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="手机号" prop="mobilePhone">
              <el-input class="input" v-model="formNatural.mobilePhone" size="small"></el-input>
            </el-form-item>
            <el-form-item label="固定电话" prop="telephone">
              <el-input class="input" v-model="formNatural.telephone" size="small"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCancleNatural">取 消</el-button>
        <el-button type="primary" @click="handleSubmitNatural">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="选择员工" :visible.sync="dialogVisibleSelect" width="60%">
      <div ref="people" class="people-box">
        <TableComponent
          class="table"
          :data="tableData || []"
          :columns="tableColumns"
          :table-option="tableOption"
          @selectionChange="selectCheckd"
          :height="peopleHeight"
        >
        </TableComponent>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleSelect = false">取 消</el-button>
        <el-button type="primary" @click="handleSelect">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import TableComponent from '@/components/Table/table'
import { dialogTableColumns, dialogTableColumnsComponty, tableColumns } from './index.js'
import { managementOrg } from '@/api/modules/propertyRight.js'
import { queryLegalRegisterType, addLegalData, queryUserByEmpName, addNaturalData } from '@/api/modules/legalAndNatural.js'
import { allArea, stateEnterpriseCapi } from '@/api/modules/propertyRight.js'
export default {
  components: { TableComponent },
  props: {
    dialogData: {
      type: Object,
      required: true
    },
  },
  watch: {
    dialogData: {
      handler(val) {
        console.log(val)
        this.dialogVisible = val.dialogVisible
        this.shareTitle = val.shareTitle
      },
      deep: true
    }
  },
  data() {
    return {
      formInline: {
        type: '',
        chiName: '',
        engName: ''
      },
      dialogVisible: false,
      shareTitle: '',
      height: null,
      ifPeople: false,
      ifCompany: false,
      dialogTableColumns,
      dialogTableColumnsComponty,
      dialogtableData: [],
      dialogtableDataComponty: [],
      dialogtableOption: {
        isShowOperate: false
      },
      searchRules: {
        type: [{required: true, message: '请选择类型', trigger: 'change'}]
      },
      options: [
        { label: '自然人', value: '0' },
        { label: '我方企业', value: '1' },
        { label: '他方企业', value: '2' }
      ],
      sendData: {
        value: '',
        code: '',
        isPerson: '',
        appointType: '',
        cmhkId: '',
        executivePartnerUcc: ''
      },
      saveName: '',
      saveCode: '',
      ucc: '',
      cmhkId: '',
      addShowBtn: false,
      // 新增他方企业弹窗参数========================
      dialogVisibleLegal: false,
      form: {
        companyChiName: '',
        location: [],
        registerType: '',
        companyEngName: '',
        stateEnterpreiseCapi: '',
        addDate: ''
      },
      locationOptions: [],
      registerTypeOptions: [],
      stateEnterpreiseCapi: [],
      prop: {
        label: 'name',
        value: 'code',
        children: 'child'
      },
      // 新增自然人弹窗参数============================
      dialogVisibleNatural: false,
      formNatural: {
        nameChi: '',
        ifcmhk: '',
        cmhkPersonId: '',
        location: [],
        email: '',
        nameEng: '',
        sex: '',
        mobilePhone: '',
        telephone: ''
      },
      ifBtn: false,
      ifCmhkPeople: false,
      ifcmhkOption: [
        { label: '是', value: '1' },
        { label: '否', value: '2' }
      ],
      rules: {
        nameChi: [{required: true, message: '请输入法人名称', trigger: 'blur'}],
        ifcmhk: [{required: true, message: '请选择是否招商局员工', trigger: 'change'}]
      },
      // 选择人弹窗
      dialogVisibleSelect: false,
      tableData: [],
      tableColumns,
      peopleHeight: null,
      tableOption: {
        isMultiSelect: true
      },
      savePeopleMsg: {}

    }
  },
  destroyed() {
    window.onresize = null
  },
  methods: {
    selectType(val) {
      this.formInline.type = val
      this.formInline.chiName = ''
      this.formInline.engName = ''
      this.dialogtableData = []
      this.dialogtableDataComponty = []
      if (this.formInline.type === '0') {
        this.ifPeople = true
        this.ifCompany = false
        this.sendData.isPerson = '1'
        this.sendData.appointType = '1'
        this.addShowBtn = true
      } else if (this.formInline.type === '1') {
        this.ifPeople = false
        this.ifCompany = true
        this.sendData.isPerson = '0'
        this.sendData.appointType = '0'
        this.addShowBtn = false
      } else if (this.formInline.type === '2') {
        this.ifPeople = false
        this.ifCompany = true
        this.sendData.isPerson = '0'
        this.sendData.appointType = '0'
        this.addShowBtn = true
      }
      this.$nextTick(() => {
        this.height = this.$refs.ref.offsetHeight
      })
      window.onresize = () => {
        this.height = this.$refs.ref.offsetHeight
      }
    },
    handleSearch(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.formInline.chiName === ''&&this.formInline.engName === '') {
            this.$message.error('中文名称或英文名称不能同时为空')
          } else {
            if (this.formInline.type === '0') {
              managementOrg(this.formInline).then(res => {
                if (res.data.code === '0') {
                  this.dialogtableData = res.data.body
                } else {
                  this.$message.error(res.data.message)
                }
              })
            } else if (this.formInline.type === '1') {
              managementOrg(this.formInline).then(res => {
                if (res.data.code === '0') {
                  this.dialogtableDataComponty = res.data.body
                } else {
                  this.$message.error(res.data.message)
                }
              })
            } else if (this.formInline.type === '2') {
              managementOrg(this.formInline).then(res => {
                if (res.data.code === '0') {
                  this.dialogtableDataComponty = res.data.body
                } else {
                  this.$message.error(res.data.message)
                }
              })
            }
          }
        } else {
          return false
        }
      })
    },
    rowClick(row) {
      this.saveName = row.chiName
      this.saveCode = row.code
      this.ucc = row.executivePartnerUcc
      this.cmhkId = row.cmhkId
    },
    handleSubmit() {
      if (this.saveName === ''||this.saveCode === '') {
        this.$message.error('请选择自然人或公司')
      } else {
        this.sendData.value = this.saveName
        this.sendData.code = this.saveCode
        this.sendData.executivePartnerUcc = this.ucc
        this.sendData.cmhkId = this.cmhkId
        this.handleCancle()
      }
    },
    handleCancle() {
      this.resetForm('searchForm')
      this.dialogtableData = []
      this.dialogtableDataComponty = []
      this.ifPeople = false
      this.ifCompany = false
      this.addShowBtn = false
      this.saveName = ''
      this.saveCode = ''
      this.ucc = ''
      this.cmhkId = ''
      this.hideDialog()
    },
    // 关闭弹窗
    hideDialog() {
      this.dialogVisible = false
      this.shareTitle = ''
      this.$emit('sendData', this.sendData)
      this.sendData.value = ''
      this.sendData.code = ''
      this.sendData.executivePartnerUcc = ''
      this.sendData.cmhkId = ''
      this.sendData.isPerson = ''
      this.sendData.appointType = ''
    },
    // 新增
    handleAdd() {
      if(this.formInline.type === '2') {
        this.dialogVisibleLegal = true
        allArea().then(res => {
          if (res.data.code === '0') {
            this.locationOptions = this.getTreeData(res.data.body)
          }
        })
        queryLegalRegisterType().then(res => {
          if (res.data.code === '0') {
            this.registerTypeOptions = res.data.body
          }
        })
        stateEnterpriseCapi().then(res => {
          if (res.data.code === '0') {
            this.stateEnterpreiseCapi = res.data.body
          }
        })
      } else if (this.formInline.type === '0') {
        this.dialogVisibleNatural = true
        allArea().then(res => {
          if (res.data.code === '0') {
            this.locationOptions = this.getTreeData(res.data.body)
          }
        })
      }
    },
    getTreeData(data){
      // 循环遍历json数据
      for(let i=0;i<data.length;i++){
        if(data[i].child.length<1){
          // children若为空数组，则将children设为undefined
          data[i].child = undefined
        }else {
          // children若不为空数组，则继续 递归调用 本方法
          this.getTreeData(data[i].child)
        }
      }
      return data
    },
    // 新增他方企业方法
    handleSubmitLegal() {
      if (this.form.companyChiName === ''&&this.form.companyEngName === '') {
        this.$message.error('必须填入注册中文名和英文名其中一项')
      } else {
        addLegalData(this.form).then(res => {
          if (res.data.code === '0') {
            this.$message.success('新增成功')
            this.handleCancleLegal()
          } else {
            this.$message.error(res.data.message)
            this.handleCancleLegal()
          }
        })
      }
    },
    handleCancleLegal() {
      this.resetForm('form')
      this.dialogVisibleLegal = false
    },
    // 新增自然人方法
    handleCancleNatural() {
      this.resetForm('formNatural')
      this.dialogVisibleNatural = false
    },
    handleSubmitNatural() {
      this.$refs['formNatural'].validate((valid) => {
        if (valid) {
          addNaturalData(this.formNatural).then(res => {
            if (res.data.code === '0') {
              this.$message.success('新增成功')
              this.resetForm('formNatural')
              this.dialogVisibleNatural  = false
            } else {
              this.$message.error(res.data.message)
            }
          })
        } else {
          return false
        }
      })
    },
    cmhkChange(val) {
      if (val === '1') {
        this.ifCmhkPeople = true
        this.ifBtn = true
      } else {
        this.ifCmhkPeople = false
        this.ifBtn = false
        this.formNatural.cmhkPersonId = ''
      }
    },
    // 选人弹窗方法===========================
    selectNum() {
      if (this.formNatural.nameChi === '') {
        this.$message.error('请输入姓名')
      } else {
        this.dialogVisibleSelect = true
        this.$nextTick(() => {
          this.peopleHeight = this.$refs.people.offsetHeight
        })
        window.onresize = () => {
          this.peopleHeight = this.$refs.people.offsetHeight
        }
        const data = {
          empName: this.formNatural.nameChi
        }
        queryUserByEmpName(data).then(res => {
          if (res.data.code === '200') {
            this.tableData = res.data.data
          } else {
            this.$message.error(res.data.message)
          }
        })
      }
    },
    selectCheckd(val) {
      if (val.length > 1) {
        this.$message.error('只能选择一条数据')
      } else  {
        this.savePeopleMsg = val[0]
      }
    },
    handleSelect() {
      this.dialogVisibleSelect = false
      this.formNatural.cmhkPersonId = this.savePeopleMsg.psId
      this.formNatural.nameChi = this.savePeopleMsg.empName
      this.formNatural.email = this.savePeopleMsg.email
      this.formNatural.sex = this.savePeopleMsg.sex
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<style lang="less" scoped>
  .table-box {
    height: 40vh;
  }
  .input {
    width: 100%;
  }
  .select {
    width: 100%;
  }
  .select-btn {
    width: calc(100% - 60px);
  }
  .people-box {
    height: 40vh;
  }
</style>